package org.android.application.marksixmanage.grab;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

import org.android.application.marksixmanage.model.LotteryResult;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import android.util.Log;

public class LotterySixGrab extends GrabAbstract {

	@Override
	public LotteryResult grabData(String url, String encode, String issueNumber) {
		String htmlStrng = getHtml(url, encode);
		return parseString(htmlStrng, encode, issueNumber);
	}

	public LotteryResult parseString(String html, String encode, String issueNumber) {
		LotteryResult resultData = null;

		if (null != html && !"".equals(html)) {
			Parser parser = Parser.createParser(html, encode);
			try {
				resultData = new LotteryResult();
				getIssue(html, resultData);
				if (!resultData.getIssueNumber().equals(issueNumber)) {
					return null;
				}
				parser.setEncoding(encode);
				NodeFilter tableFilter = new NodeClassFilter(TableTag.class);
				NodeFilter[] filters = new NodeFilter[] { tableFilter };
				OrFilter filter = new OrFilter(filters);

				NodeList nodeList = parser.parse(filter);

				TableTag tableTag = getTableTagByMap(nodeList,
						getTableCondition());

				if (tableTag == null) {
					return null;
				}

				TableRow[] rows = tableTag.getRows();

				StringBuffer results = new StringBuffer();


				for (int i = 0; i < 1; i++) {
					TableRow row = rows[i];
					TableColumn[] columns = row.getColumns();
					int count = 0;
					//TODO:可改为接口，回调适应不同的页面。
					for (TableColumn column : columns) {
						try {
							ImageTag img = (ImageTag) column.getChild(0);
							if (count == 6) {
								results.append("|");
							} else if (results.length() > 0) {
								results.append(",");
							}
							results.append(img.getAttribute("alt"));
							count++;
						} catch (Exception e) {

						}
					}
				}
				if (results.length() > 0) {
					resultData.setResultData(results.toString());
				}

			} catch (ParserException e) {
				Log.d("garb", "Parser error" + e.getMessage());
			} catch (ParseException e) {
				Log.e("grab", "Format Error" + e.getMessage());
			}

		}

		return resultData;
	}

	private TableTag getTableTagByMap(NodeList nodeList,
			Map<String, String> tableCondition) {
		
		for (int i = 0; i <= nodeList.size(); i++) {
			if (nodeList.elementAt(i) instanceof TableTag) {
				TableTag tag = (TableTag) nodeList.elementAt(i);
				if (tableCondition != null && !tableCondition.isEmpty()) {
					boolean isRight = true;
					for (String key : tableCondition.keySet()) {
						if (null == tag.getAttribute(key)) {
							if (!"null".equals(tableCondition.get(key))) {
								isRight = false;
								break;
							}
						} else if (!tag.getAttribute(key).equals(
								tableCondition.get(key))) {
							isRight = false;
							break;
						}
					}
					if (isRight) {
						if (tag.getRowCount() > 0) {
							if(tag.getChildrenHTML().indexOf("<tr align=\"center\" valign=\"middle\">")>0){
								return tag;
							}
						}
					}
				}
			}
		}
		return null;
	}

	private void getIssue(String html, LotteryResult data) throws ParseException {
		//TODO:可改为接口，回调适应不同的页面。
		int start = html.indexOf(">攪珠日期");
		if (start > 0) {
			String firstCut = html.substring(start);
			String secondCut = firstCut.substring(firstCut.indexOf("<font"),
					firstCut.indexOf("-") + 8);
			String date = secondCut.substring(secondCut.indexOf(">")+1);
			SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
			sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
			Date time = sdf.parse(date);
			SimpleDateFormat dtos = new SimpleDateFormat("yyyyMMdd");
			String issue = dtos.format(time);
			data.setIssueNumber(issue);
		}
	}

	private Map<String, String> getTableCondition() {
		Map<String, String> conditionMap = new HashMap<String, String>();
		conditionMap.put("border", "0");
		conditionMap.put("cellspacing", "0");
		conditionMap.put("cellpadding", "0");
		conditionMap.put("width", "100%");
		return conditionMap;
	}

}
